package hu.u_szeged.inf.ovrt.filelister.core.workflow;

import static hu.u_szeged.inf.ovrt.filelister.core.beans.Colors.ERROR;
import static hu.u_szeged.inf.ovrt.filelister.core.beans.Colors.INFO;
import static hu.u_szeged.inf.ovrt.filelister.core.beans.Colors.PROMPT;
import hu.u_szeged.inf.ovrt.filelister.commands.Command;
import hu.u_szeged.inf.ovrt.filelister.core.beans.ApplicationState;
import hu.u_szeged.inf.ovrt.filelister.core.exception.ModuleNotFoundException;
import hu.u_szeged.inf.ovrt.filelister.core.utils.ParameterBuilder;
import hu.u_szeged.inf.ovrt.filelister.ui.UserInterface;

import java.util.Map;

/**
 * Workflow implementation.
 */
public class SimpleWorkflow implements Workflow {
    private UserInterface ui;
    private ParameterBuilder parameterBuilder;
    private CommandFactory cmdFactory;

    private ApplicationState state;

    @Override
    public void run() {
        printWelcomeMessage();

        while (true) {
            try {
                ui.print("cmd: ", PROMPT);

                String input = "";
                String commandStr = "";
                String parameterString = "";

                input = ui.readLn();
                input = input.trim();
                input = input.replaceAll("\\s+", " ");

                if (input.contains(" ")) {
                    commandStr = input.substring(0, input.indexOf(" "));
                    parameterString = input.substring(input.indexOf(" ") + 1);

                } else {
                    commandStr = input;
                }

                Map<String, String> parameters = parameterBuilder.getParameterMap(parameterString);
                Command command = cmdFactory.getCommand(commandStr);
                command.execute(state, parameters);
            } catch (ModuleNotFoundException e) {
                ui.printLn(e.getMessage(), ERROR);
            }
        }
    }

    public void setUi(UserInterface ui) {
        this.ui = ui;
    }

    public void setParameterBuilder(ParameterBuilder parameterBuilder) {
        this.parameterBuilder = parameterBuilder;
    }

    public void setCmdFactory(CommandFactory cmdFactory) {
        this.cmdFactory = cmdFactory;
    }

    public void setState(ApplicationState state) {
        this.state = state;
    }

    private void printWelcomeMessage() {
        ui.printLn("Welcome " + System.getProperty("user.name") + "!\n", INFO);
    }
}
